from posthog.hogql.database.models import (
    DANGEROUS_NoTeamIdCheckTable,
    DateTimeDatabaseField,
    FieldOrTable,
    IntegerDatabaseField,
    StringDatabaseField,
    StringJSONDatabaseField,
    Table,
)


class LogsTable(Table):
    fields: dict[str, FieldOrTable] = {
        "uuid": StringDatabaseField(name="uuid", nullable=False),
        "team_id": IntegerDatabaseField(name="team_id", nullable=False),
        "trace_id": StringDatabaseField(name="trace_id", nullable=False),
        "span_id": StringDatabaseField(name="span_id", nullable=False),
        "body": StringDatabaseField(name="body", nullable=False),
        "attributes": StringJSONDatabaseField(name="attributes", nullable=False),
        "time_bucket": DateTimeDatabaseField(name="time_bucket", nullable=False),
        "time_minute": DateTimeDatabaseField(name="time_minute", nullable=False),
        "timestamp": DateTimeDatabaseField(name="timestamp", nullable=False),
        "observed_timestamp": DateTimeDatabaseField(name="observed_timestamp", nullable=False),
        "severity_text": StringDatabaseField(name="severity_text", nullable=False),
        "severity_number": IntegerDatabaseField(name="severity_number", nullable=False),
        "level": StringDatabaseField(name="level", nullable=False),
        "resource_attributes": StringJSONDatabaseField(name="resource_attributes", nullable=False),
        "instrumentation_scope": StringDatabaseField(name="instrumentation_scope", nullable=False),
        "event_name": StringDatabaseField(name="event_name", nullable=False),
        "service_name": StringDatabaseField(name="service_name", nullable=False),
        # internal fields for query optimization
        "_part_starting_offset": IntegerDatabaseField(name="_part_starting_offset", nullable=True, hidden=True),
        "_part_offset": IntegerDatabaseField(name="_part_offset", nullable=True, hidden=True),
        "mat_body_ipv4_matches": StringJSONDatabaseField(name="mat_body_ipv4_matches", nullable=True, hidden=True),
    }

    def to_printed_clickhouse(self, context):
        return "logs"

    def to_printed_hogql(self):
        return "logs"


class LogsKafkaMetricsTable(DANGEROUS_NoTeamIdCheckTable):
    """
    Table stores meta information about kafka consumption _not_ scoped to teams

    This is so we can find out the overall lag per partition and filter live logs accordingly
    """

    fields: dict[str, FieldOrTable] = {
        "_partition": IntegerDatabaseField(name="_partition", nullable=False),
        "_topic": StringDatabaseField(name="_topic", nullable=False),
        "max_observed_timestamp": DateTimeDatabaseField(name="max_observed_timestamp", nullable=False),
    }

    def to_printed_clickhouse(self, context):
        return "logs_kafka_metrics"

    def to_printed_hogql(self):
        return "logs_kafka_metrics"
